<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="addRolesFormVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色权限列表 -->
      <el-table :data="roleList" style="width: 100%" border stripe>
        <!-- 添加展开列 -->
        <el-table-column type="expand">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="i1"
              :class="[
                'border-bottom',
                i1 === 0 ? 'border-top' : '',
                'centerRow',
                'vcenter'
              ]"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二、 三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="i2"
                  :class="[i2 === 0 ? '' : 'border-top', 'vcenter']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="i3"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{scope.row}}
            </pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="ID"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="getRoleInfo(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delRole(scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色弹出框 -->
    <el-dialog title="添加角色" :visible.sync="addRolesFormVisible">
      <el-form :model="addRolesForm">
        <el-form-item label="角色名称" label-width="80px">
          <el-input
            v-model="addRolesForm.roleName"
            placeholder="请输入角色的名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="80px">
          <el-input
            v-model="addRolesForm.roleDesc"
            placeholder="请输入角色的描述"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addRolesFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改角色信息弹出框 -->
    <el-dialog title="修改角色信息" :visible.sync="editRolesFormVisible">
      <el-form :model="editRolesForm">
        <el-form-item label="角色名称" label-width="80px">
          <el-input
            v-model="editRolesForm.roleName"
            placeholder="请输入角色的名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="80px">
          <el-input
            v-model="editRolesForm.roleDesc"
            placeholder="请输入角色的描述"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editRolesFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 角色权限分配弹出框 -->
    <el-dialog title="分配角色权限" :visible.sync="setRightDialogVisible" @close="setRightDialogClose">
      <!-- tree 树形控件 -->
      <el-tree :data="rightsList" :props="defaultProps" show-checkbox default-expand-all node-key="id" :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <div slot="footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      roleList: [],
      // 添加角色表单对象
      addRolesForm: {},
      // 修改角色表单对象
      editRolesForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      // 角色权限列表
      rightsList: [],
      // 控制dialog弹出层
      addRolesFormVisible: false,
      editRolesFormVisible: false,
      setRightDialogVisible: false,
      // Tree 树形控件配置对象
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 三级权限 id 数组
      defKeys: [],
      // 记录角色id值
      roleId: ''
    }
  },
  methods: {
    // 获取角色权限列表
    async getRoleList() {
      const { data: res } = await this.https.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('  角色列表加载失败!')
      }
      this.roleList = res.data
    },
    // 删除角色权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$messageBox
        .confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then((res) => res)
        .catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('权限删除取消成功!')
      }
      const { data: res } = await this.https.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('权限删除失败!')
      }
      this.$message.success('权限删除成功!')
      // role 是 scope.row , 即作用域插槽中每一行的数据对象(它), 修改了它的值, 模板会局部重新渲染, 而不会整个页面渲染
      role.children = res.data
    },
    // 添加角色
    async addRoles() {
      this.addRolesFormVisible = false
      const { data: res } = await this.https.post('roles', this.addRolesForm)
      if (res.meta.status !== 201) {
        return this.$message.error('角色添加失败!')
      }
      this.$message.success('角色添加成功!')
      this.getRoleList()
    },
    // 根据ID获取角色信息
    async getRoleInfo(role) {
      const { data: res } = await this.https.get('roles/' + role.id)
      if (res.meta.status !== 200) {
        return this.$message.error('角色信息查询失败!')
      }
      this.editRolesForm = res.data
      this.editRolesFormVisible = true
    },
    // 修改角色信息
    async editRoleInfo() {
      const { data: res } = await this.https.put(
        'roles/' + this.editRolesForm.roleId,
        this.editRolesForm
      )
      if (res.meta.status !== 200) {
        return this.$message.error('角色信息修改失败!')
      }
      this.$message.success('角色信息修改成功!')
      this.editRolesFormVisible = false
      this.getRoleList()
    },
    // 删除角色
    async delRole(role) {
      const confirmResult = await this.$messageBox
        .confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then((res) => res)
        .catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('角色删除取消成功!')
      }
      var { data: res } = await this.https.delete('roles/' + role.id)
      if (res.meta.status !== 200) {
        return this.$message.error('角色删除失败!')
      }
      this.$message.success('角色删除成功!')
      this.getRoleList()
    },
    // 弹出角色权限分配对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.https.get('rights/' + 'tree')
      if (res.meta.status !== 200) {
        return this.$message.error('权限列表获取失败!')
      }
      this.rightsList = res.data
      // console.log(this.rightsList)
      this.getLeafKeys(role, this.defKeys)
      // console.log(this.defKeys)
      this.setRightDialogVisible = true
    },
    // 递归函数，获取角色的三级权限
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 关闭角色权限分配对话框触发函数
    setRightDialogClose() {
      // 清空值
      this.defKeys = []
    },
    // 修改角色权限分配
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys)
      const idStr = keys.join(',')
      // console.log(idStr)
      // console.log(this.roleId)
      const { data: res } = await this.https.post(`roles/${this.roleId}/rights`, { rids: idStr })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('角色权限分配失败!')
      }
      this.$message.success('角色权限分配成功!')
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  },
  created() {
    this.getRoleList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.border-top {
  border-top: 1px solid #ebeef5;
}
.border-bottom {
  border-bottom: 1px solid #ebeef5;
}
.centerRow {
  margin: 0 20px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
